package maple.thelittleredbook.content.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import maple.thelittleredbook.content.dto.OperationLogHistoryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import maple.thelittleredbook.content.entity.ContentOperationLog;
import maple.thelittleredbook.content.mapper.ContentOperationLogMapper;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 内容操作日志服务 - 修改版本
 */
@Slf4j
@Service
public class ContentOperationLogService {

    private final ContentOperationLogMapper operationLogMapper;

    @Autowired
    public ContentOperationLogService(ContentOperationLogMapper operationLogMapper) {
        this.operationLogMapper = operationLogMapper;
    }

    /**
     * 创建操作日志记录
     */
    public Long createOperationLog(Long contentId, String operationType,
                                   Integer totalOperations, Long createdBy) {
        ContentOperationLog Oplog = new ContentOperationLog();
        Oplog.setContentId(contentId);
        Oplog.setOperationType(operationType);
        Oplog.setOperationStatus(ContentOperationLog.STATUS_PROCESSING);
        Oplog.setTotalOperations(totalOperations);
        Oplog.setCompletedOperations(0);
        Oplog.setCreatedBy(createdBy);

        operationLogMapper.insert(Oplog);

        log.info("创建操作日志，ID: {}, 内容ID: {}, 操作类型: {}, 总操作数: {}",
                Oplog.getId(), contentId, operationType, totalOperations);

        return Oplog.getId();
    }

    /**
     * 增加已完成操作数
     */
    public synchronized void incrementCompletedOperations(Long logId) {
        ContentOperationLog Oplog = operationLogMapper.selectById(logId);
        if (Oplog != null) {
            Oplog.setCompletedOperations(Oplog.getCompletedOperations() + 1);

            // 检查是否所有操作都完成
            if (Oplog.getCompletedOperations().equals(Oplog.getTotalOperations())) {
                Oplog.setOperationStatus(ContentOperationLog.STATUS_COMPLETED);
                Oplog.setCompletedAt(LocalDateTime.now());
                log.info("操作日志完成，ID: {}, 内容ID: {}", logId, Oplog.getContentId());
            }

            operationLogMapper.updateById(Oplog);
        }
    }

    /**
     * 标记操作失败
     */
    public void markOperationFailed(Long logId, String errorMessage) {
        ContentOperationLog Oplog = operationLogMapper.selectById(logId);
        if (Oplog != null) {
            Oplog.setOperationStatus(ContentOperationLog.STATUS_FAILED);
            Oplog.setErrorMessage(errorMessage);
            Oplog.setCompletedAt(LocalDateTime.now());

            operationLogMapper.updateById(Oplog);

            log.error("操作日志失败，ID: {}, 内容ID: {}, 错误: {}",
                    logId, Oplog.getContentId(), errorMessage);
        }
    }

    /**
     * 根据内容ID查询操作日志列表
     */
    public List<ContentOperationLog> getOperationLogs(Long contentId) {
        return operationLogMapper.selectByContentId(contentId);
    }

    /**
     * 根据内容ID和操作类型查询日志
     */
    public List<ContentOperationLog> getOperationLogs(Long contentId, String operationType) {
        if (operationType != null) {
            return operationLogMapper.selectByContentIdAndType(contentId, operationType);
        } else {
            return operationLogMapper.selectByContentId(contentId);
        }
    }

    /**
     * 根据ID查询操作日志
     */
    public ContentOperationLog getOperationLog(Long logId) {
        return operationLogMapper.selectById(logId);
    }

    /**
     * 检查内容是否有进行中的操作
     */
    public boolean hasProcessingOperations(Long contentId) {
        Long count = operationLogMapper.countProcessingOperations(contentId);
        return count > 0;
    }

    /**
     * 获取操作日志历史列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param operationType 操作类型筛选
     * @param contentId 内容ID筛选
     * @param queryUserId 查询的用户ID（管理员可以查询任意用户，普通用户只能查询自己）
     * @param currentUserId 当前登录用户ID
     * @param currentUserRole 当前用户角色
     * @return 操作日志历史
     */
    public OperationLogHistoryResponse getOperationLogHistory(Integer pageNum, Integer pageSize,
                                                              String operationType, Long contentId,
                                                              Long queryUserId, Long currentUserId,
                                                              String currentUserRole) {
        // 1. 参数验证和默认值设置
        pageNum = pageNum != null && pageNum > 0 ? pageNum : 1;
        pageSize = pageSize != null && pageSize > 0 && pageSize <= 100 ? pageSize : 20;
        operationType = operationType != null && !operationType.trim().isEmpty() ? operationType : "all";

        // 2. 权限检查
        boolean isAdmin = "ADMIN".equals(currentUserRole) || "SUPERADMIN".equals(currentUserRole);
        Long finalQueryUserId;

        if (isAdmin) {
            // 管理员可以查询任意用户，如果没指定则查询所有
            finalQueryUserId = queryUserId;
        } else {
            // 普通用户只能查询自己的记录
            finalQueryUserId = currentUserId;
        }

        // 3. 创建分页对象
        Page<ContentOperationLog> page = new Page<>(pageNum, pageSize);

        // 4. 处理操作类型参数
        String finalOperationType = "all".equals(operationType) ? null : operationType;

        // 5. 查询数据库
        IPage<ContentOperationLog> result;
        if (isAdmin) {
            result = operationLogMapper.selectPageForAdmin(page, finalQueryUserId, contentId, finalOperationType);
        } else {
            result = operationLogMapper.selectPageByUserId(page, finalQueryUserId, contentId, finalOperationType);
        }

        // 6. 构建响应对象
        OperationLogHistoryResponse response = new OperationLogHistoryResponse();
        response.setTotal(result.getTotal());
        response.setTotalPages((int) Math.ceil((double) result.getTotal() / pageSize));
        response.setPageNum(pageNum);
        response.setPageSize(pageSize);
        response.setLogs(result.getRecords());

        return response;
    }
}